package com.yun.kin.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author jin
 * @Description
 * @Date 2021/3/1 14:51
 */
@Component
@Aspect
public class LogAspect {

    private final Logger logger =
            LoggerFactory.getLogger(this.getClass());
    /**
     * 定义切面
     */
    @Pointcut("execution(* com.yun.kin.blog.web.*.*(..))")
    public void log(){};

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod, (Object[]) args);

//        logger.info("-------------doBefore-----------------");
        logger.info("RequestLog : {}" +requestLog);
    }

    @After("log()")
    public void doAfter(){
//        logger.info("-------------doAfter-----------------");
    }

    @AfterReturning(returning = "result" , pointcut = "log()")
    public void doAfterReturn(Object result){
        logger.info("Result : {}" , result);
    }

    //记录日志内容
    private class RequestLog{
        private String url;           //请求URL
        private String ip;            //访问者IP
        private String classMethod;   //调用方法class
        private Object[] args;        //参数args

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }


}
